#include "imageuploader.h"
#include "appchat/accountmanager.h"
#include "account/accountuser.h"
#include <json.h>

namespace Image {

Uploader* Uploader::m_instance = 0;

Uploader* Uploader::instance(QObject *parent)
{
    if (!m_instance) {
        m_instance = new Uploader(parent);
    }
    return m_instance;
}

Uploader::Uploader(QObject *parent) :
    QObject(parent)
{
    http=new QNetworkAccessManager(this);
}

void Uploader::upload()
{
    if(filePath() == "")
        return;

//    Account::User *user = Account::Manager::instance()->user();
//    QString numFolder = QVariant(user->id()).toString();

    QFileInfo finfo(filePath());
    QNetworkRequest r(QUrl("http://upload-photo.cloud.me.zing.vn/up/" + QVariant(10003).toString()));

    QString bound="---------------------------723690991551375881941828858";
    QByteArray data(QString("--"+bound+"\r\n").toUtf8());
    data += "Content-Disposition: form-data; name=\"action\"\r\n\r\n";
    data += "\r\n";
    data += QString("--" + bound + "\r\n").toUtf8();
    data += "Content-Disposition: form-data; name=\"file\"; filename=\""+finfo.fileName()+"\"\r\n";

    QString format = finfo.suffix().toLower();
    if(format == "jpg")
        format = "jpeg";
    data += "Content-Type: image/"+ format +"\r\n\r\n";

    QFile file(finfo.absoluteFilePath());
    file.open(QIODevice::ReadOnly);
    data += file.readAll();
    data += "\r\n";
    data += QString("--" + bound + "\r\n").toUtf8();
    data += QString("--" + bound + "\r\n").toUtf8();
    data += "Content-Disposition: form-data; name=\"desc\"\r\n\r\n";
    data += "\r\n";
    r.setRawHeader(QString("Accept-Encoding").toUtf8(), QString("gzip,deflate").toUtf8());
    r.setRawHeader(QString("Content-Type").toUtf8(),QString("multipart/form-data; boundary=" + bound).toUtf8());
    r.setRawHeader(QString("Content-Lengt").toUtf8(), QString::number(data.length()).toUtf8());

    reps.push_back(http->post(r,data));
    connect(reps.at(reps.size()-1),SIGNAL(finished()),this,SLOT(onUpload()));
}

void Uploader::onUpload()
{
    for(int i=0;i<reps.size();i++){
        if(reps[i]->isFinished()){
            QString message=reps[i]->readAll();

            parserImage(message.toUtf8());
            emit setPhoto();
        }
    }

    reps.clear();
}

void Uploader::parserImage(QByteArray message)
{
    //qDebug() << "Message Parse Image upload:";
    //qDebug() << message;
    JsonReader reader;
    QTextStream stream(message);
    QVariant variant;
    if (!reader.read(stream, variant))
        return;
    if (variant.type() != QVariant::Map)
        return;

    QVariantMap map = variant.toMap();

    QVariant errorVar = map.value("error_code");
    if (errorVar.type() != QVariant::Int)
        return;
    QVariant photo_id = map.value("photo_id");
    if (photo_id.type() != QVariant::Int)
        return;

    QVariant photo_url = map.value("photo_url");
    if (photo_url.type() != QVariant::String)
        return;

    QString url =  photo_url.toString();
    sendPhotoUrl(url);

}

void Uploader::setFilePath(QString filePath)
{
    m_filePath = filePath;
}
}
